package io.zhengsh.fastjson;



import org.springframework.lang.NonNull;
import org.springframework.lang.Nullable;

import java.util.Objects;
import java.util.Optional;

public class NullPointerExceptionTest {


    static class UserDto {
        private Integer userId;

        public Integer getUserId() { return userId; }

        public void setUserId(Integer userId) { this.userId = userId; }
    }

    public static void main(String[] args) {

        // 1. 对象为空获取属性值
        try {
            UserDto userDto = null;
            System.out.println(userDto.getUserId());
        } catch (Throwable throwable) { throwable.printStackTrace();}

        // 2. 属性值为空进行 equest 比较
        try {
            UserDto userDto  = new UserDto();
            userDto.getUserId().equals(1);
        } catch (Throwable throwable) { throwable.printStackTrace();}

        // 3. 类型自动拆箱过程中发现是空值
        try {
            UserDto userDto  = new UserDto();
            test(userDto.getUserId());
        } catch (Throwable throwable) { throwable.printStackTrace();}

        // 4. 严谨的逻辑方案, 使用 Optional
        try {
            UserDto userDto = new UserDto();
            Optional.of(userDto.getUserId()).ifPresent(item -> {
                test(userDto.getUserId());
            });

            Integer userId = Optional.of(userDto.getUserId()).orElse(1);
        } catch (Throwable throwable) { throwable.printStackTrace();}

        // 4. 严谨的逻辑方案, 使用 if 判断, 并且使用 Objects 工具方法
        try {
            UserDto userDto = new UserDto();
            if (userDto != null && Objects.equals(userDto.getUserId(), 1)) {
                test(userDto.getUserId());
            }
        } catch (Throwable throwable) { throwable.printStackTrace();}

        // 5. 参数上增加 @NonNull , idea 在编译的时候会检查
    }

    public static void test(int userId) {
        System.out.println(userId);
    }

    public static void test1(@NonNull @Nullable Integer userId) {
        System.out.println(userId);
    }
}
